<?php

namespace My\Controller;

use Utuo\BackgroundController;

class ContentController extends BackgroundController {
	
	protected $catId; // 栏目id
	protected $id; // 内容id
	protected $model; // 模型
	
	// 初始化
	public function _initialize() {
		$this->setControllerTitle ( "内容管理" );
		$this->setActionTitle ( array (
				'index' => '内容设置' 
		) );
		$this->id = I ( "id", I ( 'get.id', 0, 'intval' ), "intval" );
		$this->catId = I ( "cat_id", I ( 'get.cat_id', 0, 'intval' ), "intval" );
		if($this->catId) {
			$this->model = $this->getModel($this->catId);
		    /*检查控制器扩展*/
			if(strtolower(CONTROLLER_NAME) == "content") {
			    static $flag = true;
			    if($flag) {
			    	$flag = false;
			    	$controller = A($this->getTableName($this->model['tag']));
			    	// 获取当前操作名 支持动态路由
			    	$action = ACTION_NAME.C('ACTION_SUFFIX');
			    	try{
			    		//执行当前操作
			    		$method = new \ReflectionMethod($controller, $action);
			    		$method->invoke($controller);
			    		exit();
			    	} catch (\ReflectionException $e) {
			    		// 没有此操作
			    	}
			    }
			}
		}
	}
	
	public function _empty($action) {
// 		$tableName = $this->getTableName($this->model['tag']);
// 		R($tableName.'/'.substr($action,0,-6));
		echo ":(";
	}
	
	// 列表
	public function indexAction() {
		layout ( "contentMain" );
		$data = D ( "Category" )->where(array('customer'=>$this->aid, 'is_deleted'=>0))->order('sort')->select();
		$categoryJSON = $this->getSimpleJOSN ( $data );
		$this->assign ( "categoryJSON", $categoryJSON );
		$this->display ();
	}
	
	// 头部信息重置
	protected function resetHeader($unit) {
		$this->setControllerTitle ( "{$unit}管理" );
		$this->setActionTitle ( array (
				'modify' => "修改{$unit}",
				'urlModify' => '外部链接修改',
				'newsModify' => '单页内容修改' 
		) );
		$this->setActionTitle ( 'list', "{$unit}列表", "cat_id={$this->catId}" );
		$this->setActionTitle ( 'add', "添加{$unit}", "cat_id={$this->catId}" );
		$this->setActionTitle ( 'recycle', '回收站', "cat_id={$this->catId}" );
		$this->setActionNav ( array (
				'list',
				'add',
				'recycle' 
		) );
	}
	
	// 获得内容列表
	public function listAction() {
		$category = M ( "Category" )->where ( "id=%d and customer=%d", $this->catId, $this->aid )->find ();
		$this->assign ( "category", $category );
		if ($category ["type"] == "list") {
			$modelId = $category ["model"];
			if (! $modelId) {
				$this->showMessage ( "您还没有选择模型" );
			}
			$model = M ( "Model" )->find ( $modelId );
			$this->getContentList ( $model, 0, 'list' );
			exit ();
		} elseif ($category ["type"] == "news") {
			redirect ( U ( "Content/newsModify", "id={$this->catId}" ) );
			exit ();
		} elseif ($category ["type"] == "url") {
			redirect ( U ( "Content/urlModify", "id={$this->catId}" ) );
			exit ();
		}
		$this->showMessage ( "您还没有选择栏目的类别" );
	}
	
	// 外部链接修改页
	public function urlModifyAction() {
		$this->resetHeader ();
		$this->setControllerTitle ( "栏目管理" );
		$this->removeActionNav ( array (
				"add",
				"list",
				"recycle" 
		) );
		$this->assign ( "category", $this->getOneById ( "Category" ) );
		$this->display ( "Content/Model/url" );
	}
	
	// 单页内容修改页
	public function newsModifyAction() {
		$this->resetHeader ();
		$this->setControllerTitle ( "栏目管理" );
		$this->removeActionNav ( array (
				"add",
				"list",
				"recycle" 
		) );
		$this->assign ( "category", $this->getOneById ( "Category" ) );
		$this->display ( "Content/Model/news" );
	}
	
	// 提交链接修改
	public function urlModifyPostAction() {
		$this->saveCategory ( array (
				'url' => I ( "url" ) 
		) );
	}
	
	// 提交单页内容修改
	public function newsModifyPostAction() {
		$this->saveCategory ( array (
				'news' => htmlspecialchars_decode ( I ( "news" ) ) 
		) );
	}
	
	// 添加内容
	public function addAction() {
		$model = $this->getModel ( $this->catId );
		$this->resetHeader ( $model ['unit'] );
		if ($model ['tag']) {
			$this->display ( $this->getTemplete ( $model ['tag'], 'add' ) );
		} else {
			$this->error ( "不能添加可能原因:该栏目还没有选择模型" );
		}
	}
	
	// 提交添加内容
	public function addPostAction() {
		$this->catId = I ( "category", 0, 'intval' );
		if (! $this->catId) {
			$this->ajaxError ( "栏目类型为空" );
		}
		$model = $this->getModel ( $this->catId );
		$modelName = $this->getTableName ( $model ['tag'] );
		$d = D ( $modelName );
		/* 保存基本内容信息 */
		if ($d->create ()) {
			$d->customer = $this->aid;
			unset ( $d->id );
			/* 添加前处理(模型中) */
			$content_id = $d->add ();
			if ($content_id) {
				/* 保存扩展内容信息 */
				$de = D ( $this->getExtTableName ( $modelName ) );
				if (false !== $de->create ()) {
					$de->id = $content_id;
					if ($de->add ()) {
						$this->ajaxSuccess ( '添加内容成功', null, U ( 'Content/list', 'cat_id=' . $this->catId ),3 );
					}else{
						$this->ajaxError ( $d->getError() );
					}
				}else{
					$this->ajaxError ( '扩展数据创建失败' );
				}
			}
		}
		$this->ajaxError ( $d->getError() );
	}
	
	// 获得标签名
	private function getTagNames($ids) {
		if ($ids) {
			$names = M ( "Tags" )->where ( array (
					"id" => array (
							"in",
							$ids 
					),
					"cid" => $this->aid 
			) )->getField ( "name", true );
			return join ( ',', $names );
		}
		return "";
	}
	
	// 修改列表模型信息
	public function modifyAction() {
		$id = I ( "id", 0, "intval" ); // 内容id
		$model = $this->model;
		$modelName = $this->getTableName ( $model ['tag'] );
		$m = D ( $modelName );
		$content = $m->where ( "customer=%d and id=%d", $this->aid, $id )->find (); // 基本内容信息
		$this->checkAdmin($content['customer']?$content['customer']:'-1');
		$content ['tags'] = $this->getTagNames ( $content ['tags'] );
		$content_extends = M ( $this->getExtTableName ( $modelName ) )->where ( "id=%d", $id )->find (); // 扩展内容信息
		$content = array_merge ( $content, $content_extends );
		$this->assign ( $model ['tag'], $content );
		$this->resetHeader ( $model ['unit'] );
		$this->display ( $this->getTemplete ( $model ['tag'], 'modify' ) );
	}
	
	// 修改列表模型信息
	public function modifyPostAction() {
		$this->catId = I ( "category", 0, 'intval' );
		if (! $this->catId) {
			$this->ajaxError ( "栏目类型为空" );
		}
		$model = $this->getModel ( $this->catId );
		$modelName = $this->getTableName ( $model ['tag'] );
		$d = D ( $modelName );
		/* 保存基本内容信息 */
		if ($d->create ()) {
			$d->customer = $this->aid;
			/* 更新前处理(模型中) */
			if (false !== $d->save ()) {
				/* 保存扩展内容信息 */
				$m = D ( $this->getExtTableName ( $modelName ) );
				if ($m->create ()) {
					if (false !== $m->save ()) {
						$this->ajaxSuccess ( '内容保存成功' );
					}
				}
			}
		}
		$this->ajaxError ( $d->getError() );
	}
	
	// 移除内容
	public function removePostAction() {
		$model = $this->getModel ( $this->catId );
		$modelName = $this->getTableName ( $model ['tag'] );
		$this->ajaxRemove ( $modelName );
	}
	
	// 恢复内容
	public function restorePostAction() {
		$model = $this->getModel ( $this->catId );
		$modelName = $this->getTableName ( $model ['tag'] );
		$this->ajaxRestore ( $modelName );
	}
	
	// 回收站
	public function recycleAction() {
		$model = $this->getModel ( $this->catId );
		$this->getContentList ( $model, 1, 'recycle' );
	}
	
	// 彻底删除内容
	public function deletePostAction() {
		$model = $this->getModel ( $this->catId );
		$modelName = $this->getTableName ( $model ['tag'] );
		if (M ( $modelName )->delete ( $this->id )) {
			if (! M ( $this->getExtTableName ( $modelName ) )->delete ( $this->id )) {
				$this->ajaxError ( '扩展数据删除失败' );
			}
			$this->ajaxSuccess ( '删除成功' );
		} else {
			$this->ajaxError ( '删除失败' );
		}
	}
	
	// 设置状态
	public function setStatusPostAction() {
		$status = I ( "status", 0, "intval" );
		$model = $this->getModel ( $this->catId );
		$modelName = $this->getTableName ( $model ['tag'] );
		$m = M ( $modelName );
		if ($m->where ( "id={$this->id}" )->setField ( "status", 1 - $status )) {
			$this->ajaxSuccess ();
		} else {
			$this->ajaxError ( $m->getError () );
		}
	}
	
	// 获得扩展表名
	private function getExtTableName($modelName) {
		if (! empty ( $modelName )) {
			return $modelName . "Config";
		}
		return 0;
	}
	
	// 获得模型信息
	protected function getModel($category) {
		$condition = array (
				'_string' => "this0.model = this1.id and this0.type='list'",
				'this0.customer' => $this->aid,
				'this0.id' => $category 
		);
		$model = M ()->table ( "__CATEGORY__ this0,__MODEL__ this1" )->where ( $condition )->field ( 'this1.*' )->find ();
		return $model;
	}
	
	// 获得模型表名
	private function getTableName($tag) {
		if (! empty ( $tag )) {
			return "Model" . ucfirst ( strtolower ( $tag ) );
		}
		return 0;
	}
	
	// 获得模板名称
	protected function getTemplete($tag, $action) {
		return "Content/Model/" . $tag . '/' . $action;
	}
	
	// 保存栏目
	private function saveCategory($data) {
		$m = M ( "Category" );
		if (false !== $m->where ( "id=%d", $this->catId )->save ( $data )) {
			$this->ajaxSuccess ( '保存成功' );
		} else {
			$this->ajaxError ( $m->getError () );
		}
	}
	
	// 获得内容列表
	private function getContentList($model, $is_deleted, $action) {
		$this->resetHeader ( $model ['unit'] );
		$modelName = $this->getTableName ( $model ['tag'] );
		$condition = array (
				'customer' => $this->aid,
				'is_deleted' => $is_deleted 
		);
		if ($this->catId) {
			$condition ['category'] = $this->catId;
		}
		$contentLists = M ( $modelName )->where ( $condition )->limit ( $this->getPageSize () )->page ( $this->getPage () )->select ();
		$contentCount = M ( $modelName )->where ( $condition )->count ();
		foreach ( $contentLists as $k => &$v ) {
			$v ['tags'] = $this->getTagNames ( $v ['tags'] );
		}
		$this->assign ( $model ['tag'] . "Lists", $contentLists );
		$this->assign ( $model ['tag'] . "Count", $contentCount );
		$this->showPage ( $contentCount, $this->getPageSize () );
		$this->display ( $this->getTemplete ( $model ['tag'], $action ) );
	}
	
}